package com.hualan.sfzyproject.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hualan.sfzyproject.util.R;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
//@Order(2)  // 确保 MyFilter01 在 CORS 处理之后执行
public class MyFilter01 implements Filter {

    //初始化
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    //重写doFilter: 对请求和响应做过滤操作
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //前置过滤
        System.out.println("MyFilter01执行了...");

        //放行: 将请求和响应交给下一个资源处理
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        String token = req.getHeader("token");
        String requestURI = req.getRequestURI();//获取请求路径

        System.out.println("requestURI为:" + requestURI);
        System.out.println("token为:" + token);

        if (token != null  || requestURI.contains("/user") || requestURI.contains("/consultant")){
            //2.放行: 将请求交给下一个资源处理
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            HttpServletResponse resq = (HttpServletResponse)servletResponse;
            ServletOutputStream out = resq.getOutputStream();
            R r = R.error2("请登录先后再进行操作!");
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(r);
            out.write(json.getBytes());
            out.close();
        }

        //后置过滤
        System.out.println("MyFilter01回来了...");
    }

    //销毁
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
